/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ticketManager.controller;


import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.validation.constraints.Pattern;
import ticketManager.ejb.UserAlreadyExist;
import ticketManager.ejb.UserDAO;
import ticketManager.model.UserGroup;


/**
 *
 * @author shengruoya
 */
@Named
@RequestScoped
public class CreateUserControl_Tic {
    @EJB
    UserDAO userBean_Tic;
    EntityManager em;
    
    @Pattern(regexp = "[a-z]{3}[a-z]*", message = "login should longer than 3")
    //regexp=regular expression
    private String userName;
    private String password1;
    private String password2;
    private UserGroup userGroup = UserGroup.USER;

    public UserDAO getUserBean_Tic() {
        return userBean_Tic;
    }

    public void setUserBean_Tic(UserDAO userBean_Tic) {
        this.userBean_Tic = userBean_Tic;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword1() {
        return password1;
    }

    public void setPassword1(String password1) {
        this.password1 = password1;
    }

    public String getPassword2() {
        return password2;
    }

    public void setPassword2(String password2) {
        this.password2 = password2;
    }

    public UserGroup getUserGroup() {
        return userGroup;
    }

    public void setUserGroup(UserGroup userGroup) {
        this.userGroup = userGroup;
    }
    
    
    
    public String doCreate() {
        boolean error = false;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (!password1.equals(password2)) {
            facesContext.addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "PassWord do not match",
                    "PassWord do not match"));
            return "error";
        }
        try {
            userBean_Tic.createUser(userName, password1,userGroup);
        } catch (UserAlreadyExist e) {
            System.err.println("Catching an exception" + e.getCause());
            String msg = "user" + userName + "already exists";
            facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg));
            return "error";
        }
        return "success";

    }
}
